// react项目实现预览markdown，以及代码高亮: https://blog.csdn.net/qq_43399210/article/details/122111572
// 【前端】react-markdown配置解析: https://blog.csdn.net/weixin_44589651/article/details/121044772
import ReactMarkdown from 'react-markdown'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { nightOwl } from 'react-syntax-highlighter/dist/esm/styles/prism'
import remarkGfm from 'remark-gfm'

type Props = {
  textContent: string
  className?: string
}

const ViewMarkdown = (props: Props) => {
  const { textContent, className } = props

  return (
    <ReactMarkdown
      className={className}
      // remarkGfm 不生效，暂时不知道原因
      remarkPlugins={[remarkGfm]}
      components={{
        code({ node, inline, className, children, ...props }) {
          const match = /language-(\w+)/.exec(className || '')
          return !inline && match ? (
            <SyntaxHighlighter showLineNumbers={true} style={nightOwl} language={match[1]} PreTag='div' {...props}>
              {String(children).replace(/\n$/, '')}
            </SyntaxHighlighter>
          ) : (
            <code className={className} {...props}>
              {children}
            </code>
          )
        }
      }}
    >
      {textContent}
    </ReactMarkdown>
  )
}

export default ViewMarkdown
